import SecureLS from "secure-ls";
// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

/**
 * 创建本地缓存对象 localStorage
 */
class LocalStorage {

  private static instance: boolean = false;
  private _ls: SecureLS | undefined;

  constructor() {
    if (!LocalStorage.instance) {
      this._ls = new SecureLS({
        encodingType: 'aes',
        isCompression: true,
        encryptionSecret: 'ldn'
      })
    }
  }


  private getKey(key: string) {
    return key.toUpperCase();
  }

  /**
   * @description 设置缓存
   * @param {string} key 缓存键
   * @param {*} value 缓存值
   * @param expire 过期时间
   */
  set(key: string, value: any, expire: number | null = DEFAULT_CACHE_TIME) {
    const stringData = JSON.stringify({
      value,
      expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
    });
    this._ls?.set(this.getKey(key), stringData);
  }

  /**
   * 读取缓存
   * @param {string} key 缓存键
   * @param {*=} def 默认值
   */
  get(key: string, def?: any) {
    const item = this._ls?.get(this.getKey(key));
    if (item) {
      try {
        const data = JSON.parse(item);
        const { value, expire } = data;
        // 在有效期内直接返回
        if (expire === null || expire >= Date.now()) {
          return value;
        }
        this.remove(key);
      } catch (e) {
        console.log(e);
        return def;
      }
    }
    return def;
  }

  /**
   * 从缓存删除某项
   * @param {string} key
   */
  remove(key: string) {
    this._ls?.remove(this.getKey(key));
  }

  /**
   * 清空所有缓存
   * @memberOf Cache
   */
  clear() {
    this._ls?.clear();
  }
}

class SessionStorage {

  private static instance: boolean = false;
  private _sg: Storage | undefined;

  constructor() {
    if (!SessionStorage.instance) {
      SessionStorage.instance = true;
      this._sg = window.sessionStorage;
    }
    return this;
  }


  set(key: string, value: any) {
    this._sg?.setItem(key, value);
  }

  get(key: string) {
    const item = this._sg?.getItem(key);
    return item ? item : '';
  }

  del(key: string) {
    this._sg?.removeItem(key);
  }

  clear() {
    this._sg?.clear()
  }
}

export const localStorage = new LocalStorage();
export const sessionStorage = new SessionStorage();
